package com.zyf.project.binaryproto.encoder.impl;

import com.zyf.project.binaryproto.specification.BinarySliceSpecification;
import com.zyf.project.binaryproto.specification.FieldSpecification;
import com.zyf.project.binaryproto.encoder.FieldEncoder;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * <h1>数据契约字段编码器抽象类</h1>
 * <p>实现了 {@link FieldEncoder}</p>
 *
 * @author Zhou Yifan
 */
public abstract class AbstractFieldEncoder implements FieldEncoder {

    protected BinarySliceSpecification sliceSpecification;

    protected FieldSpecification fieldSpecification;

    protected Method reader;

    public AbstractFieldEncoder(BinarySliceSpecification sliceSpecification, FieldSpecification fieldSpecification, @NotNull Method reader) {
        this.sliceSpecification = sliceSpecification;
        this.fieldSpecification = fieldSpecification;
        reader.setAccessible(true);
        this.reader = reader;
    }

    @Override
    public BinarySliceSpecification getSliceSpecification() {
        return sliceSpecification;
    }

    @Override
    public FieldSpecification getFieldSpecification() {
        return fieldSpecification;
    }

    @Override
    public Method getReader() {
        return reader;
    }

    protected Object readValue(Object dataContract) {
        try {
            return reader.invoke(dataContract);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

}
